package com.arpa.wms.handler;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.wms.domain.dto.AuthDto;
import com.arpa.wms.domain.entity.Shop;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopBaseHttpResponse;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddPopAuthTokenCreateRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddPopAuthTokenRefreshRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddPopAuthTokenCreateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddPopAuthTokenRefreshResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import static com.arpa.wms.handler.AbstractTokenManagerHandler.PDD_TOKEN_MANAGER;


/**
 * 拼多多token处理
 *
 * @author lxl
 * @since 2021-09-16
 */
@Log4j2
@Component(PDD_TOKEN_MANAGER)
public class PddTokenHandler extends AbstractTokenManagerHandler {
    String clientId = "24f4f08553284648b4653ce008345514";
    String clientSecret = "3d1269b8a012d499c90eaa59940ca6e2328795da";

    @Override
    public void refreshToken(Shop shop) {
        log.info("拼多多token刷新处理。{}",JSONUtil.toJsonStr(shop));
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddPopAuthTokenRefreshRequest request = new PddPopAuthTokenRefreshRequest();
        request.setRefreshToken(shop.getRefreshToken());
        PddPopAuthTokenRefreshResponse response = null;
        try {
            response = client.syncInvoke(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PddPopAuthTokenRefreshResponse.PopAuthTokenRefreshResponse result = response.getPopAuthTokenRefreshResponse();
        int expiresIn = result.getExpiresIn();
        DateTime gmtTokenExp = DateUtil.offset(DateUtil.date(), DateField.SECOND, expiresIn);
        String accessToken = result.getAccessToken();
        if (!StrUtil.equals(accessToken, shop.getAccessToken())) {
            String refreshToken = result.getRefreshToken();
            shop.setGmtTokenExp(gmtTokenExp);
            shop.setAccessToken(accessToken);
            shop.setRefreshToken(refreshToken);
            shopMapper.updateById(shop);
        }
    }

    /**
     * 获取token
     *
     * @param dto
     * @author liuxr
     * @date 2021/10/25 17:19
     */
    @Override
    public void getToken(AuthDto dto) {
        PopClient client = new PopHttpClient(clientId, clientSecret);

        PddPopAuthTokenCreateRequest request = new PddPopAuthTokenCreateRequest();
        request.setCode(dto.getCode());
        PddPopAuthTokenCreateResponse response = null;
        try {
            response = client.syncInvoke(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("拼多多授权信息：{}",JsonUtil.transferToJson(response));
        PopBaseHttpResponse.ErrorResponse  errorResponse = response.getErrorResponse();
        if(errorResponse!=null){
            log.error("{}:{}",errorResponse.getErrorMsg(),errorResponse.getSubMsg());
            throw new ServiceException(errorResponse.getErrorMsg() + ":" + errorResponse.getSubMsg());
        }else{
            PddPopAuthTokenCreateResponse.PopAuthTokenCreateResponse result =  response.getPopAuthTokenCreateResponse();
            String asscessToken = result.getAccessToken();
            String refreshToken = result.getRefreshToken();
            int expiresIn =  result.getExpiresIn();
            DateTime gmtTokenExp = DateUtil.offset(DateUtil.date(), DateField.SECOND, expiresIn);
            String ownerId = result.getOwnerId();
            Shop shop = shopMapper.selectOne(Wrappers.lambdaQuery(Shop.class).eq(Shop::getUserId,ownerId).last("limit 1"));
            if(null==shop){
                log.error("授权失败，系统中找不到对应的店铺信息。userId:{}",ownerId);
                throw new ServiceException("授权失败，系统中找不到对应的店铺信息");
            }
            shop.setAccessToken(asscessToken);
            shop.setRefreshToken(refreshToken);
            shop.setGmtTokenExp(gmtTokenExp);
            shopMapper.updateById(shop);
        }


    }
}


